package com.atguigu.mr.flow;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * @description:
 * @create: 2019-12-15 22:24
 * @author: baojinlong
 **/
public class FlowCountReducer extends Reducer<Text, FlowBean, Text, FlowBean> {
    private FlowBean nowValue = new FlowBean();

    @Override
    protected void reduce(Text key, Iterable<FlowBean> values, Context context) throws IOException, InterruptedException {
        // 1.累加求和 18867144238 {22,44} 18867144238 {23,66} 上行流量求和/下行流量求和/总的求和
        long sumUpFlow = 0;
        long sumDownFlow = 0;
        for (FlowBean value : values) {
            sumUpFlow += value.getUpFlow();
            sumDownFlow += value.getDownFlow();
        }
        assembleSumValue(nowValue, sumUpFlow, sumDownFlow);
        // 2.写出
        context.write(key, nowValue);
    }

    /**
     * 封装当前value的值
     *
     * @param nowValue
     * @param sumUpFlow
     * @param sumDownFlow
     */
    private void assembleSumValue(FlowBean nowValue, long sumUpFlow, long sumDownFlow) {
        nowValue.setUpFlow(sumUpFlow);
        nowValue.setDownFlow(sumDownFlow);
        nowValue.setSumFlow(sumUpFlow + sumDownFlow);
    }
}
